<?php

namespace App\Http\Controllers\Home;

use App\Http\Controllers\Controller;
use App\Model\Admin\CategoriesModel;
use App\Model\Admin\NewsModel;
use App\Model\ConfigModel;
use Illuminate\Http\Request;

class NewsController extends Controller
{
    /**
     * 页面
     *
     * @param string $category_id
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function index($category_id = '')
    {
        $data = [];
        if ($category_id != ''){
            $where = [
                ['is_show','=',1],
                ['news_type','=',$category_id]
            ];
            $category = CategoriesModel::findOrFail($category_id);
            $data['seo']['config_title'] = $category->name;
            $data['seo']['config_keywords'] = $category->keywords;
            $data['seo']['config_description'] = $category->description;
        } else {
            $where = [
                ['is_show','=',1]
            ];
            $data['seo'] =  ConfigModel::where('config_type','news')
                ->first()->toArray();
        }
        $data['news_type'] = CategoriesModel::where('pid',2)->select(['id','name'])->get();
        $data['news_list'] = NewsModel::where($where)
            ->orderBy('created_at','desc')
            ->select(['id','created_at','news_title','img','abstract'])
            ->paginate(6);

        $data['latest_news'] = NewsModel::where('is_show',1)
            ->orderBy('created_at','desc')
            ->select(['id','news_title','created_at'])
            ->where('recommend',1)
            ->get();
        return view('front.news_list')->with('data',$data);
    }

    /**
     * 详情
     *
     * @param NewsModel $newsModel
     * @param $id
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function detail(NewsModel $newsModel, $id)
    {
        $data['info'] = $newsModel->findOrFail($id);
        $data['latest_news'] = $newsModel->where('is_show',1)
            ->select(['id','news_title','created_at'])
            ->where('recommend',1)
            ->take(5)
            ->get();
        $data['prev'] = $newsModel->where('id','<',$id)
            ->where('is_show',1)
            ->orderBy('id','desc')
            ->first(['id','news_title']);
        $data['next'] = $newsModel->where('id','>',$id)
            ->where('is_show',1)
            ->orderBy('id','asc')
            ->first(['id','news_title']);

        return view('front.news_detail')->with('data',$data);
    }
}
